import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/song.dart';
import '../widgets/search_bar_widget.dart';
import '../widgets/song_list_widget.dart';
import '../widgets/mini_player_widget.dart';
import '../widgets/player_sheet_widget.dart';
import '../services/music_player_service.dart';

class SearchScreen extends StatefulWidget {
  final String? initialKeyword;
  const SearchScreen({super.key, this.initialKeyword});

  @override
  State<SearchScreen> createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> {
  List<Song> _searchResults = [];
  bool _isSearching = false;
  String _currentQuery = '';
  List<String> _searchHistory = [];
  final List<String> _hotKeywords = [
    '周杰伦', '邓紫棋', '凤凰传奇', '张杰', '周深', '薛之谦', '毛不易', '陈奕迅', '许嵩',
    '林俊杰', '张学友', '王菲', '李荣浩', '周华健', '王力宏', '张靓颖', '汪苏泷', '鹿晗',
  ];
  
  // SearchBarWidget的GlobalKey
  final GlobalKey<SearchBarWidgetState> _searchBarKey = GlobalKey<SearchBarWidgetState>();
  
  static const String _searchHistoryKey = 'search_history';

  @override
  void initState() {
    super.initState();
    _loadSearchHistory();
    if (widget.initialKeyword != null && widget.initialKeyword!.isNotEmpty) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _searchBarKey.currentState?.searchWithKeyword(widget.initialKeyword!);
      });
    }
  }

  void _onSearchResults(List<Song> results, String query) {
    setState(() {
      _searchResults = results;
      _currentQuery = query;
      _isSearching = false;
      
      // 添加到搜索历史
      if (query.isNotEmpty && !_searchHistory.contains(query)) {
        _searchHistory.insert(0, query);
        if (_searchHistory.length > 10) {
          _searchHistory.removeLast();
        }
        _saveSearchHistory();
      }
    });
  }

  void _onSearchStarted() {
    setState(() {
      _isSearching = true;
      _searchResults.clear(); // 清空之前的搜索结果
      _currentQuery = ''; // 清空当前查询
    });
  }

  void _onSearchBarTapped() {
    // 当点击搜索框时，清空之前的搜索结果
    setState(() {
      _searchResults.clear();
      _currentQuery = '';
      _isSearching = false;
    });
  }

  void _showPlayerSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      // 默认桌面端会限制 BottomSheet 宽度，这里使用无限约束，
      // 让其根据父级（窗口）实时变化以达到自适应全屏。
      constraints: const BoxConstraints(
        maxWidth: double.infinity,
        maxHeight: double.infinity,
      ),
      useSafeArea: true,
      builder: (context) => const PlayerSheetWidget(),
    );
  }

  void _onSongTap(Song song, int index) {
    final playerService = Provider.of<MusicPlayerService>(context, listen: false);
    playerService.setPlaylist(_searchResults, startIndex: index);
  }

  void _clearSearchHistory() {
    setState(() {
      _searchHistory.clear();
    });
    _saveSearchHistory();
  }

  // 加载搜索历史
  Future<void> _loadSearchHistory() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final history = prefs.getStringList(_searchHistoryKey) ?? [];
      setState(() {
        _searchHistory = history;
      });
    } catch (e) {
      print('加载搜索历史失败: $e');
    }
  }

  // 保存搜索历史
  Future<void> _saveSearchHistory() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setStringList(_searchHistoryKey, _searchHistory);
    } catch (e) {
      print('保存搜索历史失败: $e');
    }
  }

  // 从搜索历史中删除指定项
  void _removeFromHistory(String query) {
    setState(() {
      _searchHistory.remove(query);
    });
    _saveSearchHistory();
  }

  // 点击搜索历史项进行搜索
  void _searchFromHistory(String query) {
    _searchBarKey.currentState?.searchWithKeyword(query);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // 在返回前失去焦点，防止键盘重新弹出
        FocusScope.of(context).unfocus();
        return true;
      },
      child: GestureDetector(
        onTap: () {
          // 点击空白区域时失去焦点
          FocusScope.of(context).unfocus();
        },
        child: Scaffold(
          appBar: AppBar(
            title: const Text(
              '搜索音乐',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            backgroundColor: Theme.of(context).colorScheme.surface,
            foregroundColor: Theme.of(context).colorScheme.onSurface,
          ),
          body: Column(
            children: [
              // 主要内容区域
              Expanded(
                child: Column(
                  children: [
                    // 搜索栏
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: SearchBarWidget(
                        key: _searchBarKey,
                        onSearchResults: _onSearchResults,
                        onSearchStarted: _onSearchStarted,
                        onTap: _onSearchBarTapped,
                      ),
                    ),
          
          // 稳定音乐源提示
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16.0),
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Theme.of(context).colorScheme.primary.withOpacity(0.1),
                  Theme.of(context).colorScheme.secondary.withOpacity(0.1),
                ],
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
              ),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: Theme.of(context).colorScheme.primary.withOpacity(0.2),
                width: 1,
              ),
            ),
            child: Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(6),
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.primary,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.verified,
                    size: 16,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: RichText(
                    text: TextSpan(
                      style: TextStyle(
                        fontSize: 13,
                        color: Theme.of(context).colorScheme.onSurface,
                      ),
                      children: [
                        TextSpan(
                          text: '推荐快速源：',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            color: Theme.of(context).colorScheme.primary,
                          ),
                        ),
                         TextSpan(
                          text: '米兔音乐',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            color: Theme.of(context).colorScheme.primary,
                          ),
                        ),
                        const TextSpan(text: '、'),
                        TextSpan(
                          text: '布谷音乐',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            color: Theme.of(context).colorScheme.primary,
                          ),
                        ),
                        //换行
                        const TextSpan(text: '\n'),
                        TextSpan(
                          text: '推荐稳定源：',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            color: Theme.of(context).colorScheme.primary,
                          ),
                        ),
                        TextSpan(
                          text: '网易云音乐',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            color: Theme.of(context).colorScheme.primary,
                          ),
                        ),
                        const TextSpan(text: '、'),
                        TextSpan(
                          text: '酷我音乐',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            color: Theme.of(context).colorScheme.primary,
                          ),
                        ),
                        const TextSpan(text: '、'),
                        TextSpan(
                          text: 'JOOX',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            color: Theme.of(context).colorScheme.primary,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Icon(
                  Icons.info_outline,
                  size: 16,
                  color: Theme.of(context).colorScheme.primary.withOpacity(0.7),
                ),
              ],
            ),
          ),
                    const SizedBox(height: 8),
                    // 主要内容区域
                    Expanded(
                      child: _buildMainContent(),
                    ),
                  ],
                ),
              ),
              
              // 迷你播放控制栏
              Consumer<MusicPlayerService>(
                builder: (context, playerService, child) {
                  if (playerService.currentSong == null) {
                    return const SizedBox.shrink();
                  }
                  return MiniPlayerWidget(
                    onTap: _showPlayerSheet,
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildMainContent() {
    if (_isSearching) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('搜索中...'),
          ],
        ),
      );
    }

    if (_searchResults.isNotEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Text(
              '搜索结果 (${_searchResults.length})',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          const SizedBox(height: 8),
          Expanded(
            child: SongListWidget(
              songs: _searchResults,
              onSongTap: _onSongTap,
            ),
          ),
        ],
      );
    }

    if (_currentQuery.isNotEmpty && _searchResults.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.search_off,
              size: 80,
              color: Theme.of(context).colorScheme.primary.withOpacity(0.5),
            ),
            const SizedBox(height: 16),
            Text(
              '没有找到相关音乐',
              style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                color: Theme.of(context).colorScheme.onSurface.withOpacity(0.6),
              ),
            ),
            const SizedBox(height: 8),
            Text(
              '尝试使用其他关键词搜索',
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).colorScheme.onSurface.withOpacity(0.4),
              ),
            ),
          ],
        ),
      );
    }

    // 显示搜索建议
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 搜索历史
          if (_searchHistory.isNotEmpty) ...[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '搜索历史',
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                TextButton(
                  onPressed: _clearSearchHistory,
                  child: const Text('清空'),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _searchHistory.map((keyword) {
                return GestureDetector(
                  onLongPress: () {
                    // 长按删除搜索历史项
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: const Text('删除搜索历史'),
                          content: Text('确定要删除 "$keyword" 吗？'),
                          actions: [
                            TextButton(
                              onPressed: () => Navigator.of(context).pop(),
                              child: const Text('取消'),
                            ),
                            TextButton(
                              onPressed: () {
                                _removeFromHistory(keyword);
                                Navigator.of(context).pop();
                              },
                              child: const Text('删除'),
                            ),
                          ],
                        );
                      },
                    );
                  },
                  child: ActionChip(
                    label: Text(keyword),
                    onPressed: () {
                      // 点击触发搜索
                      _searchFromHistory(keyword);
                    },
                    backgroundColor: Theme.of(context).colorScheme.surfaceContainer,
                  ),
                );
              }).toList(),
            ),
            const SizedBox(height: 24),
          ],
          
          // 热门搜索
          Text(
                  '热门搜索',
                  style: Theme.of(context).textTheme.titleMedium,
                ),
          const SizedBox(height: 12),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: _hotKeywords.map((keyword) {
              return ActionChip(
                    label: Text(keyword),
                    onPressed: () {
                      // 触发搜索
                      _searchBarKey.currentState?.searchWithKeyword(keyword);
                    },
                backgroundColor: Theme.of(context).colorScheme.primary.withOpacity(0.1),
                labelStyle: TextStyle(
                  color: Theme.of(context).colorScheme.primary,
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }
}
